package com.testitems.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.testitems.common.web.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录认证失败返回错误信息
 * @author GFH
 * @since 2021-11-20
 */
@Component
public class EntryPointUnauthorizedHandler implements AuthenticationEntryPoint {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        final PrintWriter writer = response.getWriter();
        final Result<String> result = Result.fail("未登录或登录失效");
        writer.write(objectMapper.writeValueAsString(result));
        writer.flush();
        writer.close();
    }
}
